import React, { Fragment, PureComponent } from 'react';
import { connect } from 'dva';
import { Badge, Button, Card, Col, DatePicker, Form, Input, Modal, Row } from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
import moment from 'moment';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};

/* eslint react/no-multi-comp:0 */
@connect(({ surlog, loading }) => ({
  surlog,
  loading: loading.models.surlog,
}))
@Form.create()
class Surlog extends PureComponent {
  state = {
    expandForm: false,
    selectedRows: [],
    detailVisible: false,
    detailsData: {},
    endTime: null,
    startTime: null,
    endOpen: false,
    formValues: {},
  };

  columns = [
    // {
    //   title: '操作人',
    //   dataIndex: 'userName',
    // },
    // {
    //   title: '用户名',
    //   dataIndex: 'userCode',
    // },
    {
      title: '第三方系统名称',
      dataIndex: 'serviceName',
    },
    // {
    //   title: '文件名称',
    //   dataIndex: 'fileName',
    // },

    {
      title: '操作类型',
      dataIndex: 'operateType',
    },
    {
      title: '操作内容',
      dataIndex: 'operateContent',
    },
    {
      title: '请求URI',
      dataIndex: 'requestUri',
      width: '30%',
    },
    {
      title: '客户端标识',
      dataIndex: 'userAgent',
      width: '30%',
    },
    {
      title: '操作时间',
      render: (text, record) => moment(text.createTime).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.detailHandelVisible(true, text)}>详情</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.pageList();
  }

  // 分页查询列表
  pageList(data, pageSize = 10, pageNum = 0) {
    const { dispatch } = this.props;
    const values = {
      fileName: (data && data.fileName) || '',
      startTime: (data && data.startTime) || '',
      endTime: (data && data.endTime) || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'surlog/queryPageList',
      payload: values,
    });
  }

  handleStandardTableChange = (pagination, filters, sorter) => {
    // 分页请求
    const { formValues } = this.state;
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  detailHandelVisible = (flag, text) => {
    this.setState({
      detailVisible: !!flag,
      detailsData: text,
    });
  }; //查看

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const params = {
        fileName: fieldsValue.fileName || '',
        startTime:
          fieldsValue.startTime && moment(fieldsValue.startTime).format('YYYY-MM-DD HH:mm'),
        endTime: fieldsValue.endTime && moment(fieldsValue.endTime).format('YYYY-MM-DD HH:mm'),
      };
      this.setState({
        formValues: params,
      });
      this.pageList(params);
    });
  };

  disabledStartDate = startTime => {
    const { endTime } = this.state;
    if (!startTime || !endTime) {
      return false;
    }
    return startTime.valueOf() > endTime.valueOf();
  };

  disabledEndDate = endTime => {
    const { startTime } = this.state;
    if (!endTime || !startTime) {
      return false;
    }
    return endTime.valueOf() <= startTime.valueOf();
  };

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  };

  onStartChange = value => {
    this.onChange('startTime', value);
  };

  onEndChange = value => {
    this.onChange('endTime', value);
  };

  handleStartOpenChange = open => {
    if (!open) {
      this.setState({ endOpen: true });
    }
  };

  handleEndOpenChange = open => {
    this.setState({ endOpen: open });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { startTime, endTime, endOpen } = this.state;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          {/* <Col md={8} sm={24}>
            <FormItem label="文件名称">
              {getFieldDecorator('fileName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col> */}

          <Col md={12} sm={24}>
            <FormItem key="startTime" {...this.formLayout} label="操作时间">
              {getFieldDecorator('startTime', {
                rules: [{ required: false, message: '选择开始时间！' }],
                initialValue: startTime,
              })(
                <DatePicker
                  disabledDate={this.disabledStartDate}
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="选择开始时间"
                  onChange={this.onStartChange}
                  onOpenChange={this.handleStartOpenChange}
                />
              )}
              <span> -- </span>
              {getFieldDecorator('endTime', {
                rules: [{ required: false, message: '请选择结束时间！' }],
                initialValue: endTime,
              })(
                <DatePicker
                  showTime
                  disabledDate={this.disabledEndDate}
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择结束时间"
                  onChange={this.onEndChange}
                  open={endOpen}
                  onOpenChange={this.handleEndOpenChange}
                />
              )}
            </FormItem>
          </Col>

          <Col md={4} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      surlog: { dataqueryPageList },
      loading,
    } = this.props;
    const { selectedRows, detailVisible, detailsData } = this.state;
    const detailsMethods = {
      detailHandelVisible: this.detailHandelVisible,
    };
    return (
      <PageHeaderWrapper title="用户操作">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={dataqueryPageList}
              columns={this.columns}
              hideRowSelection={true}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.id}
            />
            {detailsData && detailsData.id ? (
              <Details
                {...detailsMethods}
                detailVisible={detailVisible}
                detailsData={detailsData}
              />
            ) : null}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

class Details extends PureComponent {
  render() {
    const { detailVisible, detailHandelVisible, detailsData } = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看详情"
        visible={detailVisible}
        onOk={() => detailHandelVisible()}
        onCancel={() => detailHandelVisible()}
        footer={[
          <Button key="back" type="primary" onClick={() => detailHandelVisible()}>
            返回
          </Button>,
        ]}
        className={styles.viewMore}
      >
        <Row>
          <Col md={12}>
            <FormItem {...formLayout} label="操作人姓名">
              {detailsData.userName}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="操作人用户名">
              {detailsData.userCode}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="第三方系统名称">
              {detailsData.serviceName}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="第三方系统IP地址">
              {detailsData.ipAddr}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="客户端标识">
              {detailsData.userAgent}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="操作时间">
              {detailsData.createTime
                ? moment(detailsData.createTime).format('YYYY-MM-DD HH:mm:ss')
                : null}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="网络访问状态">
              {detailsData.status}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="日志类型">
              {{ 1: '同步', 2: '接口' }[detailsData.logType] || detailsData.logType}
            </FormItem>
          </Col>
          {/* <Col md={12}>
            <FormItem {...formLayout} label="文件名称">
              {detailsData.fileName}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="文件大小">
              {detailsData.fileSize}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="文件ID">
              {detailsData.originFileId}
            </FormItem>
          </Col> */}

          <Col md={12}>
            <FormItem {...formLayout} label="操作类型">
              {detailsData.operateType}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...formLayout} label="操作内容">
              {detailsData.operateContent}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="异常消息">
              {detailsData.exceptionMsg}
            </FormItem>
          </Col>
          {/* <Col md={12}>
            <FormItem {...formLayout} label="目标对象">
              {detailsData.targetObject}
            </FormItem>
          </Col> */}

          <Col md={24}>
            <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="请求URI">
              {detailsData.requestUri}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="请求方法">
              {detailsData.method}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="访问参数">
              {detailsData.params}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 21 }} label="登录token">
              {detailsData.loginToken}
            </FormItem>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default Surlog;
